package com.learn.practice.security;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.practice.pojo.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    public static ConcurrentHashMap<String, Object> jwtTokenCache = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, Long> mobileCodeCache = new ConcurrentHashMap<>();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //拿到登录用户信息
        LoginUser userDetails = (LoginUser)authentication.getPrincipal();

        //生成jwt(token)
        Map<String, Object> map = new HashMap<>();
        map.put("uid", userDetails.getUsername());
        map.put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
        String jwtToken = "jwt_" + JWTUtil.createToken(map, "1234".getBytes());
        map.put("token",jwtToken);
        map.put("userObject",userDetails);
        //将用户信息保存到redis
        jwtTokenCache.put(userDetails.getUsername(),map);

        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("message","成功");
        result.put("data",jwtToken);
        //输出结果
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}
